import winrm


class MyWin:
    '''
    连接远程windows主机，host:远程ip；username:远程主机用户；password:远程主机密码
    '''

    def __init__(self, host, username, password, connect=None):
        self.host = host
        self.username = username
        self.password = password
        self.connect = connect
        self.get_connect()

    def get_connect(self):
        self.connect = winrm.Session('http://' + self.host + ':5985/wsman', auth=(self.username, self.password))
        return self.connect

    def get_files(self, rule, path):
        '''
        获取远程指定路径下符合规则的文件
        :param rule: 制定规则例如：*.dim.xml，即获取以.dim.xml后缀的文件
        :param path: 远程文件所在路径
        :return: 返回路径下所有符合规则的文件名
        '''
        # 确定盘符
        drive_letter = path.split(':')[0]
        file_names = self.connect.run_cmd('{0}: & cd {1} & dir /b {2}'.format(drive_letter, path, rule))
        file_names = file_names.std_out.decode().split('\r\n')
        return file_names

    def get_file_connect(self, file_name, path):
        '''

        :param file_name:
        :param path: 远程文件所在路径
        :return: 放回文件内容(注意：文件过大会消耗内存)
        '''
        # 确定盘符
        drive_letter = path.split(':')[0]
        connect = self.connect.run_cmd(
            '{0}: & cd {1} & type "{2}"'.format(drive_letter, path, file_name)).std_out.decode()
        return connect
